import uuid
import time
from typing import Dict, Optional
from concurrent.futures import ThreadPoolExecutor

from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import threading
import logging


import sys
import os

# 确保当前目录在Python搜索路径中（解决模块导入问题）
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
    sys.path.append(current_dir)

from client_sensor import SensorClient
from client_transmission import TransmissionClient


class SensorServer:
    def __init__(self,
                 transmission_config: str = "./configs/transmission.yaml",
                 flask_host: str = "0.0.0.0",
                 flask_port: int = 9001,
                 max_workers: int = 4):
        """初始化传感器服务类（由C++托管）"""
        # 1. Flask服务基础配置
        self.app = Flask(__name__)
        CORS(self.app)  # 允许跨域访问
        self.flask_host = flask_host
        self.flask_port = flask_port
        self.transmission_config = transmission_config

        # 2. 传感器客户端相关属性
        self.sensor_client: Optional[SensorClient] = None  # 传感器客户端实例
        self.client_lock = threading.Lock()  # 传感器客户端操作锁
        self.is_sensor_running = False  # 采集线程运行状态

        # 3. 显示任务相关属性
        self.display_tasks: Dict[str, Dict] = {}  # 任务存储字典
        self.task_lock = threading.Lock()  # 任务操作锁
        self.executor = ThreadPoolExecutor(max_workers=max_workers)  # 任务线程池

        # 4. 传感器数据缓存
        self.sensor_data = {
            "compass": {}, "posture": {}, "depth": {}, "guidance": {},
            "humiture": {}, "seatrac": {}, "gps": {}, "dvl": {}
        }

        # 5. 注册所有API路由（保留核心功能接口）
        self._register_routes()

        # 6. 启动Flask服务（后台线程，由C++托管时自动运行）
        self._start_flask_in_background()

    def _register_routes(self):
        """注册所有Flask路由（保留核心功能，不删除任何接口）"""
        # 首页路由
        self.app.add_url_rule('/', 'index', self.index)
        # 服务启停路由（保留，供C++间接调用或应急使用）
        self.app.add_url_rule('/start', 'start_sensor_server', self.start_sensor_server, methods=["GET"])
        self.app.add_url_rule('/stop', 'stop_sensor_server', self.stop_sensor_server, methods=["GET"])

        # 传感器控制路由
        self.app.add_url_rule('/sensor/connect', 'connect_sensor', self.connect_sensor, methods=["POST"])
        self.app.add_url_rule('/sensor/start', 'start_collection', self.start_collection, methods=["POST"])
        self.app.add_url_rule('/sensor/stop', 'stop_collection', self.stop_collection, methods=["POST"])
        self.app.add_url_rule('/sensor/status', 'get_sensor_status', self.get_sensor_status, methods=["GET"])
        self.app.add_url_rule('/sensor/disconnect', 'disconnect_sensor', self.disconnect_sensor, methods=["POST"])
        self.app.add_url_rule('/sensor/playback', 'playback_history_data', self.playback_history_data, methods=["GET"])
        self.app.add_url_rule('/sensor/select', 'select_all_same_timestamp', self.select_all_same_timestamp,
                              methods=["GET"])
        self.app.add_url_rule('/sensor/samplerate', 'adjust_sampling_rate', self.adjust_sampling_rate, methods=["POST"])
        self.app.add_url_rule('/sensor/connect_sensors', 'sensor_connect_sensors', self.sensor_connect_sensors,
                              methods=["POST"])

        # 显示任务路由
        self.app.add_url_rule('/display/connect/<task_id>', 'connect_display', self.connect_display, methods=["POST"])
        self.app.add_url_rule('/display/task', 'create_task', self.create_task, methods=["POST"])
        self.app.add_url_rule('/display/task/<task_id>', 'update_task', self.update_task, methods=["PUT"])
        self.app.add_url_rule('/display/task/<task_id>', 'delete_task', self.delete_task, methods=["DELETE"])
        self.app.add_url_rule('/display/task/<task_id>/status', 'get_task_status', self.get_task_status,
                              methods=["GET"])
        self.app.add_url_rule('/display/task/<task_id>/result', 'get_task_result', self.get_task_result,
                              methods=["GET"])
        self.app.add_url_rule('/display/process/<task_id>', 'process_data', self.process_data, methods=["POST"])

        # 传感器数据查询与接收路由
        self.app.add_url_rule('/sensor/compass', 'receive_compass', self.receive_compass, methods=["POST"])
        self.app.add_url_rule('/sensor/posture', 'receive_posture', self.receive_posture, methods=["POST"])
        self.app.add_url_rule('/sensor/depth', 'receive_depth', self.receive_depth, methods=["POST"])
        self.app.add_url_rule('/sensor/guidance', 'receive_guidance', self.receive_guidance, methods=["POST"])
        self.app.add_url_rule('/sensor/humiture', 'receive_humiture', self.receive_humiture, methods=["POST"])
        self.app.add_url_rule('/sensor/seatrac', 'receive_seatrac_usbl', self.receive_seatrac_usbl, methods=["POST"])
        self.app.add_url_rule('/sensor/dvl', 'receive_dvl', self.receive_dvl, methods=["POST"])
        self.app.add_url_rule('/sensor/gps', 'receive_gps', self.receive_gps, methods=["POST"])

        self.app.add_url_rule('/sensor/compass', 'get_compass', self.get_compass, methods=["GET"])
        self.app.add_url_rule('/sensor/posture', 'get_posture', self.get_posture, methods=["GET"])
        self.app.add_url_rule('/sensor/depth', 'get_depth', self.get_depth, methods=["GET"])
        self.app.add_url_rule('/sensor/guidance', 'get_guidance', self.get_guidance, methods=["GET"])
        self.app.add_url_rule('/sensor/humiture', 'get_humiture', self.get_humiture, methods=["GET"])
        self.app.add_url_rule('/sensor/dvl', 'get_dvl', self.get_dvl, methods=["GET"])
        self.app.add_url_rule('/sensor/seatrac', 'get_seatrac_usbl', self.get_seatrac_usbl,
                              methods=["GET"])
        self.app.add_url_rule('/sensor/gps', 'get_gps', self.get_gps, methods=["GET"])
        self.app.add_url_rule('/sensor/all', 'get_all_sensors', self.get_all_sensors, methods=["GET"])

    def _start_flask_in_background(self):
        """在后台线程启动Flask服务（不阻塞C++主线程）"""
        def run_flask():
            self.app.run(
                host=self.flask_host,
                port=self.flask_port,
                debug=False,
                use_reloader=False  # 禁用自动重载，避免多进程冲突
            )
        # 启动后台线程
        flask_thread = threading.Thread(target=run_flask, daemon=True)
        flask_thread.start()
        logging.info(f"Flask服务已在后台启动（{self.flask_host}:{self.flask_port}）")

    def _init_sensor_client(self, host: str = "127.0.0.1", port: int = 8888) -> SensorClient:
        """初始化SensorClient"""
        with self.client_lock:
            if self.sensor_client is None:
                self.sensor_client = SensorClient(host=host, port=port)
                self.sensor_client.connect()
            return self.sensor_client

    def _create_display_task(self, config_data: Dict) -> str:
        """创建显示任务"""
        task_id = str(uuid.uuid4())[:8]
        with self.task_lock:
            try:
                if "config_file" in config_data:
                    client = TransmissionClient(config_file=config_data["config_file"])
                else:
                    client = TransmissionClient(config_file=self.transmission_config)
                    for key, value in config_data.items():
                        if hasattr(client, key):
                            setattr(client, key, value)
                    client.connect()

                self.display_tasks[task_id] = {
                    "client": client,
                    "status": "idle",
                    "result": {}
                }
                return task_id
            except Exception as e:
                raise ValueError(f"创建任务失败：{str(e)}")

    def _update_display_task(self, task_id: str, config_data: Dict) -> bool:
        """更新显示任务"""
        with self.task_lock:
            if task_id not in self.display_tasks:
                return False
            task = self.display_tasks[task_id]
            if task["status"] == "processing":
                raise ValueError("任务正在处理中，无法修改")

            try:
                new_client = TransmissionClient(config_file=self.transmission_config)
                for key, value in config_data.items():
                    if hasattr(new_client, key):
                        setattr(new_client, key, value)
                new_client.connect()

                task["client"] = new_client
                task["status"] = "idle"
                task["result"] = {}
                return True
            except Exception as e:
                raise ValueError(f"修改任务失败：{str(e)}")

    def _delete_display_task(self, task_id: str) -> bool:
        """删除显示任务"""
        with self.task_lock:
            if task_id not in self.display_tasks:
                return False
            task = self.display_tasks[task_id]
            if hasattr(task["client"], "close"):
                task["client"].close()
            del self.display_tasks[task_id]
            return True

    def _get_display_task(self, task_id: str) -> Optional[Dict]:
        """获取显示任务"""
        with self.task_lock:
            return self.display_tasks.get(task_id, None)

    def _run_evaluate_async(self, task_id: str):
        """异步执行任务评估"""
        task = self._get_display_task(task_id)
        if not task or task["status"] != "idle":
            return

        with self.task_lock:
            task["status"] = "processing"

        try:
            client = task["client"]
            client.evaluate()
            result = {
                "volume_data": client.volume_data,
                "slices_data": client.slices_data,
                "estimated_3d_grid": client.estimated_3d_grid if hasattr(client, "estimated_3d_grid") else None
            }
            with self.task_lock:
                task["status"] = "success"
                task["result"] = result
        except Exception as e:
            with self.task_lock:
                task["status"] = "failed"
                task["result"] = {"error_msg": str(e)}

    def _handle_sensor_data(self, sensor_type: str):
        """通用传感器数据处理"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({"status": "error", "msg": f"{sensor_type}数据为空"}), 400

            current_time = time.time()
            current_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            self.sensor_data[sensor_type] = {
                "data": data,
                "timestamp": current_time,
                "update_time": current_time_str
            }

            return jsonify({"status": "success", "msg": f"{sensor_type}数据已接收"})
        except Exception as e:
            return jsonify({"status": "error", "msg": f"{sensor_type}数据处理失败：{str(e)}"}), 500

    # -------------------------- 路由对应方法（全部保留，确保功能完整） --------------------------
    def index(self):
        return render_template('/index/index.html')

    def start_sensor_server(self):
        if self.is_sensor_running:
            return jsonify({
                "status": "already_running",
                "success": False,
                "msg": "传感器服务已在运行，无需重复启动"
            }), 400

        try:
            if not self.sensor_client:
                self.sensor_client = self._init_sensor_client(host="127.0.0.1", port=8888)
            if not self.sensor_client.connected:
                self.sensor_client.connect()
                if not self.sensor_client.connected:
                    raise Exception("自动连接C++服务器（127.0.0.1:8888）失败")
            logging.info("✅ 自动连接C++服务器成功")

            with self.client_lock:
                connect_sensor_result = self.sensor_client.connect_sensors()

            if connect_sensor_result.get("status") != "success":
                raise Exception(f"自动连接传感器失败：{connect_sensor_result.get('msg', '未知错误')}")
            logging.info("✅ 自动连接传感器成功")

            self.is_sensor_running = True

            return jsonify({
                "status": "success",
                "success": True,
                "msg": "传感器服务启动成功（已自动完成C++连接+传感器连接）",
                "c_plus_server": "127.0.0.1:8888（已连接）",
                "collect_interval_ms": 100
            }), 200

        except Exception as e:
            if self.sensor_client and self.sensor_client.connected:
                self.sensor_client.close()
            self.is_sensor_running = False
            return jsonify({
                "status": "start_failed",
                "success": False,
                "msg": f"传感器服务启动失败：{str(e)}",
                "error_detail": str(e)
            }), 500

    def stop_sensor_server(self):
        if not self.is_sensor_running:
            return jsonify({
                "status": "not_running",
                "success": False,
                "msg": "传感器服务未运行，无需停止"
            }), 400

        self.is_sensor_running = False

        try:
            with self.client_lock:
                if self.sensor_client and self.sensor_client.connected:
                    self.sensor_client.stop_collection()
                    self.sensor_client.close()
            logging.info("✅ 已停止C++采集+断开传感器+断开C++连接")
        except Exception as e:
            logging.error(f"❌ 停止连接时异常：{str(e)}")
            return jsonify({
                "status": "stop_partial_failed",
                "success": False,
                "msg": f"采集线程已停止，但断开连接时异常：{str(e)}"
            }), 500

        self.sensor_client = None
        self.is_sensor_running = False

        return jsonify({
            "status": "success",
            "success": True,
            "msg": "传感器服务已完全停止（采集线程+传感器+C++连接均已断开）",
            "remaining_data": "保留最后一次采集数据（可通过/sensor/all查询）"
        }), 200

    # 传感器控制方法（全部保留）
    def connect_sensor(self):
        try:
            data = request.get_json() or {}
            host = data.get("host", "127.0.0.1")
            port = data.get("port", 8888)
            client = self._init_sensor_client(host=host, port=port)

            if client.connected:
                return jsonify({
                    "status": "success",
                    "msg": f"已连接C++服务器 {host}:{port}",
                })
            else:
                return jsonify({
                    "status": "error",
                    "msg": f"连接C++服务器 {host}:{port} 失败",
                }), 500
        except Exception as e:
            return jsonify({
                "status": "error",
                "msg": f"连接失败：{str(e)}",
            }), 500

    def start_collection(self):
        if not self.sensor_client or not self.sensor_client.connected:
            return jsonify({
                "status": "error",
                "msg": "未连接C++服务器，请先调用/connect接口"
            }), 400

        try:
            data = request.get_json() or {}
            interval_ms = data.get("interval_ms", 100)
            with self.client_lock:
                result = self.sensor_client.start_collection(interval_ms=interval_ms)
            return jsonify(result)
        except Exception as e:
            return jsonify({
                "status": "error",
                "msg": f"启动采集失败：{str(e)}"
            }), 500

    def stop_collection(self):
        if not self.sensor_client or not self.sensor_client.connected:
            return jsonify({
                "status": "error",
                "msg": "未连接C++服务器，请先调用/connect接口"
            }), 400

        try:
            with self.client_lock:
                result = self.sensor_client.stop_collection()
            return jsonify(result)
        except Exception as e:
            return jsonify({
                "status": "error",
                "msg": f"停止采集失败：{str(e)}"
            }), 500

    def get_sensor_status(self):
        if not self.sensor_client or not self.sensor_client.connected:
            return jsonify({
                "status": "error",
                "msg": "未连接C++服务器，请先调用/connect接口"
            }), 400

        try:
            with self.client_lock:
                result = self.sensor_client.get_status()
            return jsonify(result)
        except Exception as e:
            return jsonify({
                "status": "error",
                "msg": f"查询状态失败：{str(e)}"
            }), 500

    def disconnect_sensor(self):
        if not self.sensor_client:
            return jsonify({
                "status": "success",
                "msg": "未初始化连接，无需断开"
            })

        try:
            with self.client_lock:
                self.sensor_client.close()
                self.sensor_client = None
            return jsonify({
                "status": "success",
                "msg": "已断开与C++服务器的连接"
            })
        except Exception as e:
            return jsonify({
                "status": "error",
                "msg": f"断开连接失败：{str(e)}"
            }), 500

    def playback_history_data(self):
        if not self.sensor_client or not self.sensor_client.connected:
            return jsonify({
                "status": "error",
                "msg": "未连接C++服务器，请先调用/connect接口"
            }), 400

        try:
            start_time = request.args.get("start_time")
            end_time = request.args.get("end_time")
            data_type = request.args.get("type", "all")

            if not start_time or not end_time:
                return jsonify({
                    "status": "error",
                    "msg": "缺少必要参数：start_time或end_time"
                }), 400

            with self.client_lock:
                result = self.sensor_client.playback_history_data(
                    start_time=start_time,
                    end_time=end_time,
                    data_type=data_type
                )
            return jsonify(result)
        except Exception as e:
            return jsonify({
                "status": "error",
                "msg": f"回放历史数据失败：{str(e)}"
            }), 500

    def select_all_same_timestamp(self):
        if not self.sensor_client or not self.sensor_client.connected:
            return jsonify({
                "status": "error",
                "msg": "未连接C++服务器，请先调用/connect接口"
            }), 400

        try:
            timestamp = request.args.get("timestamp")
            if not timestamp:
                return jsonify({
                    "status": "error",
                    "msg": "缺少必要参数：timestamp"
                }), 400

            with self.client_lock:
                result = self.sensor_client.select_all_same_timestamp(timestamp=timestamp)
            return jsonify(result)
        except Exception as e:
            return jsonify({
                "status": "error",
                "msg": f"查询同时间戳数据失败：{str(e)}"
            }), 500

    def adjust_sampling_rate(self):
        if not self.sensor_client or not self.sensor_client.connected:
            return jsonify({
                "status": "error",
                "msg": "未连接C++服务器，请先调用/connect接口"
            }), 400

        try:
            data = request.get_json() or {}
            rate = data.get("rate")
            if rate is None or not isinstance(rate, int) or rate <= 0:
                return jsonify({
                    "status": "error",
                    "msg": "无效参数：rate（必须是正整数）"
                }), 400

            with self.client_lock:
                result = self.sensor_client.adjust_sampling_rate(rate=rate)
            return jsonify(result)
        except Exception as e:
            return jsonify({
                "status": "error",
                "msg": f"调整采样率失败：{str(e)}"
            }), 500

    def sensor_connect_sensors(self):
        if not self.sensor_client or not self.sensor_client.connected:
            return jsonify({
                "status": "error",
                "msg": "未连接C++服务器，请先调用/sensor/connect接口"
            }), 400

        try:
            with self.client_lock:
                result = self.sensor_client.connect_sensors()
            return jsonify(result)
        except Exception as e:
            return jsonify({
                "status": "error",
                "msg": f"连接传感器失败：{str(e)}"
            }), 500

    # 显示任务方法（全部保留）
    def connect_display(self, task_id):
        task = self._get_display_task(task_id)
        if not task:
            return jsonify({"status": "error", "msg": f"任务ID不存在: {task_id}"}), 404

        try:
            client = task["client"]
            client.connect()
            with self.task_lock:
                task["status"] = "idle"

            return jsonify({
                "status": "success" if client.connected else "error",
                "msg": f"任务{task_id}通讯{'成功' if client.connected else '失败'}"
            })
        except Exception as e:
            return jsonify({"status": "error", "msg": str(e)}), 500

    def create_task(self):
        try:
            config_data = request.get_json() or {}
            task_id = self._create_display_task(config_data)
            return jsonify({
                "status": "success",
                "task_id": task_id,
                "msg": f"任务创建成功，ID: {task_id}"
            })
        except Exception as e:
            return jsonify({"status": "error", "msg": str(e)}), 400

    def update_task(self, task_id):
        try:
            config_data = request.get_json() or {}
            success = self._update_display_task(task_id, config_data)
            if not success:
                return jsonify({"status": "error", "msg": f"任务ID不存在: {task_id}"}), 404
            return jsonify({"status": "success", "msg": f"任务{task_id}修改成功"})
        except Exception as e:
            return jsonify({"status": "error", "msg": str(e)}), 400

    def delete_task(self, task_id):
        success = self._delete_display_task(task_id)
        if not success:
            return jsonify({"status": "error", "msg": f"任务ID不存在: {task_id}"}), 404
        return jsonify({"status": "success", "msg": f"任务{task_id}删除成功"})

    def get_task_status(self, task_id):
        task = self._get_display_task(task_id)
        if not task:
            return jsonify({"status": "error", "msg": f"任务ID不存在: {task_id}"}), 404

        return jsonify({
            "status": "success",
            "task_id": task_id,
            "task_status": task["status"],
            "result_summary": {
                "has_volume": bool(task["result"].get("volume_data")),
                "has_slices": bool(task["result"].get("slices_data"))
            }
        })

    def get_task_result(self, task_id):
        task = self._get_display_task(task_id)
        if not task:
            return jsonify({"status": "error", "msg": f"任务ID不存在: {task_id}"}), 404

        if task["status"] != "success":
            return jsonify({
                "status": "error",
                "msg": f"任务未完成，当前状态: {task['status']}",
                "task_id": task_id
            }), 400

        return jsonify({
            "status": "success",
            "task_id": task_id,
            "result": task["result"]
        })

    def process_data(self, task_id):
        task = self._get_display_task(task_id)
        if not task:
            return jsonify({"status": "error", "msg": f"任务ID不存在: {task_id}"}), 404

        if task["status"] == "processing":
            return jsonify({
                "status": "warning",
                "msg": f"任务{task_id}正在处理中，请勿重复触发"
            })

        self.executor.submit(self._run_evaluate_async, task_id)
        return jsonify({
            "status": "success",
            "msg": f"任务{task_id}已提交处理，请通过/status接口查询进度"
        })

    # 传感器数据接收与查询方法（全部保留）
    def receive_compass(self):
        return self._handle_sensor_data("compass")

    def receive_posture(self):
        return self._handle_sensor_data("posture")

    def receive_depth(self):
        return self._handle_sensor_data("depth")

    def receive_guidance(self):
        return self._handle_sensor_data("guidance")

    def receive_humiture(self):
        return self._handle_sensor_data("humiture")

    def receive_seatrac_usbl(self):
        return self._handle_sensor_data("seatrac")

    def receive_gps(self):
        return self._handle_sensor_data("gps")

    def receive_dvl(self):
        return self._handle_sensor_data("dvl")

    def get_compass(self):
        compass_data = self.sensor_data.get("compass", {})
        if not compass_data:
            return jsonify({
                "status": "warning",
                "msg": "暂无指南针数据",
                "data": {}
            })

        return jsonify({
            "status": "success",
            "msg": "已获取最新指南针数据",
            "data": compass_data["data"],
            "update_time": compass_data.get("update_time", "")
        })

    def get_posture(self):
        posture_data = self.sensor_data.get("posture", {})
        if not posture_data:
            return jsonify({
                "status": "warning",
                "msg": "暂无姿态数据",
                "data": {}
            })

        return jsonify({
            "status": "success",
            "msg": "已获取最新姿态数据",
            "data": posture_data["data"],
            "update_time": posture_data.get("update_time", "")
        })

    def get_depth(self):
        depth_data = self.sensor_data.get("depth", {})
        if not depth_data:
            return jsonify({
                "status": "warning",
                "msg": "暂无深度数据",
                "data": {}
            })

        return jsonify({
            "status": "success",
            "msg": "已获取最新深度数据",
            "data": depth_data["data"],
            "update_time": depth_data.get("update_time", "")
        })

    def get_guidance(self):
        guidance_data = self.sensor_data.get("guidance", {})
        if not guidance_data:
            return jsonify({
                "status": "warning",
                "msg": "暂无光纤惯性导航系统数据",
                "data": {}
            })

        return jsonify({
            "status": "success",
            "msg": "已获取最新光纤惯性导航系统数据",
            "data": guidance_data["data"],
            "update_time": guidance_data.get("update_time", "")
        })

    def get_humiture(self):
        humiture_data = self.sensor_data.get("humiture", {})
        if not humiture_data:
            return jsonify({
                "status": "warning",
                "msg": "暂无温湿度传感器数据",
                "data": {}
            })

        return jsonify({
            "status": "success",
            "msg": "已获取最新温湿度传感器数据",
            "data": humiture_data["data"],
            "update_time": humiture_data.get("update_time", "")
        })

    def get_dvl(self):
        dvl_data = self.sensor_data.get("dvl", {})
        if not dvl_data:
            return jsonify({
                "status": "warning",
                "msg": "暂无DVL数据",
                "data": {}
            })

        return jsonify({
            "status": "success",
            "msg": "已获取DVL传感器数据",
            "data": dvl_data["data"],
            "update_time": dvl_data.get("update_time", "")
        })

    def get_seatrac_usbl(self):
        seatrac_data = self.sensor_data.get("seatrac", {})
        if not seatrac_data:
            return jsonify({
                "status": "warning",
                "msg": "暂无seatracUSBL水声定位系统数据",
                "data": {}
            })

        return jsonify({
            "status": "success",
            "msg": "已获取最新seatracUSBL水声定位系统数据",
            "data": seatrac_data["data"],
            "update_time": seatrac_data.get("update_time", "")
        })

    def get_gps(self):
        gps_data = self.sensor_data.get("gps", {})
        if not gps_data:
            return jsonify({
                "status": "warning",
                "msg": "暂无GPS数据",
                "data": {}
            })

        return jsonify({
            "status": "success",
            "msg": "已获取最新GPS数据",
            "data": gps_data["data"],
            "update_time": gps_data.get("update_time", "")
        })

    def get_all_sensors(self):
        latest_update = max(
            self.sensor_data["compass"].get("timestamp", 0),
            self.sensor_data["posture"].get("timestamp", 0),
            self.sensor_data["depth"].get("timestamp", 0),
            self.sensor_data["guidance"].get("timestamp", 0),
            self.sensor_data["humiture"].get("timestamp", 0),
            self.sensor_data["seatrac"].get("timestamp", 0),
            self.sensor_data["gps"].get("timestamp", 0)
        )

        return jsonify({
            "status": "success",
            "msg": "已获取所有传感器最新数据",
            "data": {
                sensor_type: {
                    "data": data.get("data", {}),
                    "update_time": data.get("update_time", "")
                } for sensor_type, data in self.sensor_data.items()
            },
            "latest_update": latest_update
        })


# 全局实例化（供C++调用）
sensor_server = SensorServer(
    transmission_config="./configs/transmission.yaml",
    flask_host="0.0.0.0",
    flask_port=9001,
    max_workers=4
)
logging.info("SensorServer：实例化完成，已由C++托管")


# 模块单独运行时的测试入口（C++环境下无需执行）
if __name__ == "__main__":
    try:
        print("SensorServer：当前为独立测试模式")
        while True:
            time.sleep(0.01)
    except KeyboardInterrupt:
        print("SensorServer：检测到退出指令")
    finally:
        if sensor_server.is_sensor_running:
            sensor_server.stop_sensor_server()
        print("SensorServer：程序已退出")